package com.jiac.coderunner.util;

import com.jiac.coderunner.entity.TableInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

public class CreateUtils {

    public static String defaultFloder = "/ftl";

    public static void generateFile(Template template,String outdir,Object obj,String fileName,boolean standardFloder){

        Writer writer = null;
        try {
            Map<String,TableInfo> data = (Map<String, TableInfo>) obj;
            TableInfo table = data.get("table");
            File outFloder = new File(outdir+"/"+table.getCamelName());
            if (!outFloder.exists()) {
                outFloder.mkdirs();
            }
            File file = null;
            if (standardFloder) {
                file = new File(outdir+"/"+table.getCamelName()+"/"+table.getClsName()+fileName);
            } else {
                file = new File(outdir+"/"+table.getClsName()+fileName);
            }
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            template.process(obj,writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

    }
}
